package com.morgan.recyclerviewdemo.itemdecoration

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.view.View
import androidx.annotation.ColorInt
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.morgan.recyclerviewdemo.entity.IClassificateTag
import com.morgan.recyclerviewdemo.utils.DeviceUtil

/**
 *description：
 *<br>author：caowugao
 *<br>time：2020/7/12 0012 13:46
 */
class ClassificationItemDecoration<TAG : IClassificateTag>(var mHeaderViewCount : Int, var mTags : List<TAG>, var mTagHeight : Int,  var mTagFontSize : Float, @ColorInt var mTagColor : Int, @ColorInt var mTagBackgroungColor : Int) : RecyclerView.ItemDecoration() {

    private val mPaint : Paint
    private val mTextBounds : Rect
    init {
        mPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mTextBounds = Rect()
    }

    constructor(context : Context,tags : List<TAG>) : this(0, tags, DeviceUtil.dp2px(context, 30f), DeviceUtil.sp2Px(context, 16f), Color.GRAY, Color.LTGRAY){

    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val params = view.layoutParams as? RecyclerView.LayoutParams ?: return
        val position = params.viewLayoutPosition - mHeaderViewCount
        if (mTags == null || mTags.isEmpty()
            || position < 0 || position >= mTags.size) {
            super.getItemOffsets(outRect, view, parent, state)
            return
        }

        val tag = mTags[position]
        if (tag == null || tag.getTag() == null ) {
            super.getItemOffsets(outRect, view, parent, state)
            return
        }

       if (position == 0 && tag.needShowHoverTop()) {//需要显示悬停顶部
           outRect.set(0, mTagHeight, 0, 0)
           return
       }

        if (position != 0 && tag.needShow()) {//非悬停位置的，需要显示tag
            val preTag = mTags[position - 1]
            if (preTag != null && !tag.getTag().equals(preTag.getTag())) {//相邻的tag不相同，说明是新的分类, 需要显示tag
                outRect.set(0, mTagHeight, 0, 0)
                return
            }
        }

        super.getItemOffsets(outRect, view, parent, state)
    }



    override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        //最后调用 绘制在最上层

        if (mTags == null || mTags.isEmpty()) {
            super.onDrawOver(c, parent, state)
            return
        }
       val layoutManager = parent.layoutManager as? LinearLayoutManager
        if (layoutManager == null) {
            super.onDrawOver(c, parent, state)
            return
        }
        val position = layoutManager.findFirstVisibleItemPosition() - mHeaderViewCount
        if (position < 0 || position >= mTags.size) {
            super.onDrawOver(c, parent, state)
            return
        }
        val tag = mTags[position]
        //不能用 View child = parent.getChildAt(pos);
        val child = parent.findViewHolderForLayoutPosition(position + mHeaderViewCount)?.itemView
        if (tag == null || tag.getTag() == null || !tag.needShowHoverTop() || child == null) {
            return
        }
        val params = child.layoutParams as? RecyclerView.LayoutParams
        if (params == null) {
           return
        }
        var isTranslated = false
        if (position + 1 < mTags.size) {
            val nextTag = mTags[position + 1]
            if (nextTag != null && nextTag.getTag() != null && nextTag.needShow()) {
                if (child.height + child.top < mTagHeight) {
                    c.save()
                    isTranslated = true
                    c.translate(0f, (child.height + child.top - mTagHeight).toFloat())
                }
            }
        }



        mPaint.color = mTagBackgroungColor
        c.drawRect(
            parent.paddingLeft + params.leftMargin  + child.translationX ,
            parent.paddingTop.toFloat(),
            (parent.right - parent.paddingRight).toFloat(),
            (parent.paddingTop + mTagHeight).toFloat(),
            mPaint
        )
        mPaint.color = mTagColor
        mPaint.textSize = mTagFontSize
        val text = tag.getTag()
        mPaint.getTextBounds(text, 0, text.length, mTextBounds)
        c.drawText(
            text, parent.paddingLeft + params.leftMargin  + child.translationX + child.paddingLeft.toFloat(),
            (parent.paddingTop + mTagHeight - (mTagHeight / 2 - mTextBounds.height() / 2)).toFloat(),
            mPaint
        )
        if (isTranslated) {
            c.restore()  //恢复画布到之前保存的状态
        }
    }

    //这里需要绘制每一个分类的tag
    override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        if (mTags == null || mTags.isEmpty()) {
            super.onDraw(c, parent, state)
            return
        }
        val childCount = parent.childCount
        val rang = 0 until childCount
        for (i in rang) {
            val child = parent.getChildAt(i)
            val params = child.layoutParams as RecyclerView.LayoutParams
            val position = params.viewLayoutPosition - mHeaderViewCount
            if (position < 0 || position >= mTags.size) {
                super.onDraw(c, parent, state)
                continue
            }
            val tag = mTags[position]
            if (tag == null || tag.getTag() == null) {
                super.onDraw(c, parent, state)
                continue
            }
            if (position == 0 && tag.needShow()) {
                drawTag(c,parent, child, params, tag.getTag())
                continue
            }
            val preTag =  mTags[position - 1]
            if (preTag != null && preTag.getTag() != null && preTag.needShow() && !preTag.getTag().equals(tag.getTag())) {
                drawTag(c, parent, child, params, tag.getTag())
            } else {
                super.onDraw(c, parent, state)
            }
        }
    }

    private fun drawTag(
        c: Canvas,
        parent: RecyclerView,
        child: View,
        params: RecyclerView.LayoutParams,
        tag: String
    ) {
        val parentPaddingLeft = parent.paddingLeft
        val parentPaddingRight = parent.paddingRight
        val childTop = child.top
//        val childBottom = child.bottom
        val childPaddingLeft = child.paddingLeft
//        val childPaddingRight = child.paddingRight
        val childTranslationX = child.translationX
        val childTranslationY = child.translationY
        val parentWidth = parent.width

        mPaint.color = mTagBackgroungColor
        c.drawRect(parentPaddingLeft + params.leftMargin  + childTranslationX, childTop - mTagHeight + childTranslationY, parentWidth - parentPaddingRight - params.rightMargin + childTranslationX, childTop + childTranslationY, mPaint)


        mPaint.getTextBounds(tag, 0, tag.length, mTextBounds)
        mPaint.color = mTagColor
        mPaint.textSize = mTagFontSize
        c.drawText(tag, parentPaddingLeft + params.leftMargin + childPaddingLeft + childTranslationX, childTop - (mTagHeight - mTextBounds.height())/2 + childTranslationY, mPaint)

    }
}